package com.louis.iread.adapter;

import android.app.Activity;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.louis.iread.R;
import com.louis.iread.bean.Article;
import com.louis.iread.skin.SkinMgr;

import java.util.List;

/**
 * Created by louis on 17-10-19.
 */

public class ArticleListAdapter extends BaseAdapter {
    private Activity context;
    private LayoutInflater inflater;
    private int layoutId;
    private int variableId;
    private int mArticleIndex = 0;
    private List<Article> mArticleList;

    public ArticleListAdapter(Activity context, int layoutId, List<Article> list, int resId, int articleIndex) {
        this.context = context;
        this.layoutId = layoutId;
        this.mArticleList = list;
        this.variableId = resId;
        inflater = LayoutInflater.from(context);
        this.mArticleIndex = articleIndex;
    }

    @Override
    public int getCount() {
        return mArticleList.size();
    }

    @Override
    public Object getItem(int position) {
        return mArticleList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        ViewDataBinding dataBinding = null;
        if (view == null) {
            dataBinding = DataBindingUtil.inflate(inflater, layoutId, parent, false);
            view = dataBinding.getRoot();
            view.setTag(dataBinding);
        }else{
            dataBinding = (ViewDataBinding) view.getTag();
        }
        ImageView imageView = (ImageView) view.findViewById(R.id.download_state);
        Article article = mArticleList.get(position);
        if (article.isDownload()) {
            imageView.setImageResource(R.drawable.yes_green);
        } else {
            imageView.setImageResource(R.drawable.yes_gray);
        }

        ImageView positionView = (ImageView) view.findViewById(R.id.read_position);
//        Log.e("===========", "position = " + position);
        if (mArticleIndex == position) {
            positionView.setVisibility(View.VISIBLE);
        } else {
            positionView.setVisibility(View.INVISIBLE);
        }

        dataBinding.setVariable(variableId, mArticleList.get(position));
        SkinMgr.getInstance().applyView(view);
        TextView articleTitle = (TextView) view.findViewById(R.id.article_title);
        articleTitle.setText(mArticleList.get(position).getTitle());
        return view;
    }
}
